from flask import Blueprint, render_template, request, flash, redirect, url_for, jsonify
from models import db, RequirementClassification, RequirementPool, RequirementType, HierarchyConfig
from utils.form_utils import ClassificationForm
from utils.calc_utils import generate_req_id, calculate_priority, get_full_path
from datetime import datetime, timedelta
from utils.export_utils import export_to_excel


requirements_bp = Blueprint('requirements', __name__, url_prefix='/requirements')

@requirements_bp.route('/classify', methods=['GET', 'POST'])
def classify():
    form = ClassificationForm()
    
    # 动态加载层级选项
    form.hierarchy_node_id.choices = [
        (h.node_id, f"{h.level}: {h.code} - {h.name}") 
        for h in HierarchyConfig.query.filter_by(is_active=True).all()
    ]
    
    # 动态加载类型选项
    form.type_id.choices = [
        (t.type_id, t.name) 
        for t in RequirementType.query.all()
    ]
    
    if form.validate_on_submit():
        # 获取层级节点
        node = HierarchyConfig.query.filter_by(node_id=form.hierarchy_node_id.data).first()
        if not node:
            flash('无效的业务层级', 'danger')
            return render_template('requirements/classify.html', form=form)
        
        # 生成完整路径
        full_path = get_full_path(node)
        
        # 生成需求ID
        req_id = generate_req_id(
            node.code, 
            form.type_id.data.split('-')[-1],
            form.request_time.data or datetime.utcnow()
        )
        
        # 创建需求分类
        classification = RequirementClassification(
            req_id=req_id,
            node_id=node.node_id,
            type_id=form.type_id.data,
            full_path=full_path,
            value_metric=form.value_metric.data,
            impact_dimensions=form.impact_dimensions.data
        )
        
        # 创建需求池条目
        pool = RequirementPool(
            req_id=req_id,
            request_time=form.request_time.data or datetime.utcnow(),
            expected_solve_time=form.expected_solve_time.data,
            business_value=int(form.business_value.data),
            complexity=int(form.complexity.data),
            urgency=int(form.urgency.data),
            status='已登记',
            type_code=form.type_id.data,
            description=form.description.data,
            solution_owner=form.solution_owner.data,
            status_update_time=datetime.utcnow()
        )
        
        # 计算优先级
        pool.priority = calculate_priority(
            pool.business_value,
            pool.urgency,
            pool.complexity
        )
        
        db.session.add(classification)
        db.session.add(pool)
        db.session.commit()
        
        flash(f'需求 {req_id} 创建成功', 'success')
        return redirect(url_for('requirements.detail', req_id=req_id))
    
    # 设置默认时间
    if not form.request_time.data:
        form.request_time.data = datetime.utcnow()
    if not form.expected_solve_time.data:
        form.expected_solve_time.data = datetime.utcnow() + timedelta(days=7)
    
    return render_template('requirements/classify.html', form=form)

@requirements_bp.route('/detail/<req_id>')
def detail(req_id):
    classification = RequirementClassification.query.get_or_404(req_id)
    pool = RequirementPool.query.get(req_id) or RequirementPool(req_id=req_id)
    return render_template('requirements/detail.html', 
                          classification=classification, 
                          pool=pool)

@requirements_bp.route('/kanban')
def kanban():
    # 按状态分组的需求
    statuses = ['已登记', '评估中', '审批', '开发', '测试', '已交付', '业务闭环']
    status_groups = {}
    for status in statuses:
        status_groups[status] = RequirementPool.query.filter_by(status=status).all()
    
    # 风险需求（滞留超过7天）
    risk_date = datetime.utcnow() - timedelta(days=7)
    risk_requirements = RequirementPool.query.filter(
        RequirementPool.status != '业务闭环',
        RequirementPool.status_update_time < risk_date
    ).all()
    
    return render_template('requirements/kanban.html', 
                          status_groups=status_groups,
                          risk_requirements=risk_requirements,
                          now=datetime.utcnow())

@requirements_bp.route('/<req_id>/update_status', methods=['POST'])
def update_status(req_id):
    pool = RequirementPool.query.get_or_404(req_id)
    new_status = request.json.get('status')
    
    if new_status not in ['已登记', '评估中', '审批', '开发', '测试', '已交付', '业务闭环']:
        return jsonify({'success': False, 'message': '无效的状态'}), 400
    
    # 更新状态
    pool.status = new_status
    pool.status_update_time = datetime.utcnow()
    db.session.commit()
    
    return jsonify({'success': True, 'new_status': new_status})

@requirements_bp.route('/delete/<req_id>', methods=['POST'])
def delete_requirement(req_id):
    classification = RequirementClassification.query.get(req_id)
    pool = RequirementPool.query.get(req_id)
    
    if classification:
        db.session.delete(classification)
    if pool:
        db.session.delete(pool)
    
    db.session.commit()
    flash('需求删除成功', 'success')
    return redirect(url_for('requirements.kanban'))

@requirements_bp.route('/export', methods=['GET'])
def export_requirements():
    # 获取所有需求（包括分类和需求池信息）
    requirements = db.session.query(
        RequirementClassification, RequirementPool
    ).join(
        RequirementPool, RequirementClassification.req_id == RequirementPool.req_id
    ).all()
    
    # 转换为字典列表
    req_list = []
    for classification, pool in requirements:
        req_dict = {
            "req_id": classification.req_id,
            "request_time": pool.request_time.strftime('%Y-%m-%d %H:%M'),
            "expected_solve_time": pool.expected_solve_time.strftime('%Y-%m-%d %H:%M') if pool.expected_solve_time else "",
            "business_value": pool.business_value,
            "complexity": pool.complexity,
            "urgency": pool.urgency,
            "priority": pool.priority,
            "status": pool.status,
            "description": pool.description,
            "solution": pool.solution,
            "solution_owner": pool.solution_owner,
            "type_code": pool.type_code,
            "full_path": classification.full_path,
            "value_metric": classification.value_metric,
            "impact_dimensions": classification.impact_dimensions,
            "status_update_time": pool.status_update_time.strftime('%Y-%m-%d %H:%M') if pool.status_update_time else ""
        }
        req_list.append(req_dict)
    
    # 列名映射
    columns_mapping = {
        "req_id": "需求ID",
        "request_time": "提出时间",
        "expected_solve_time": "期望解决时间",
        "business_value": "业务价值",
        "complexity": "复杂度",
        "urgency": "紧急度",
        "priority": "优先级",
        "status": "状态",
        "description": "需求描述",
        "solution": "解决方案",
        "solution_owner": "解决负责人",
        "type_code": "类型编码",
        "full_path": "业务层级路径",
        "value_metric": "价值度量",
        "impact_dimensions": "影响维度",
        "status_update_time": "状态更新时间"
    }
    
    return export_to_excel(req_list, "需求记录", columns_mapping)